package com.yt.order.provider.service.impl;

import com.google.common.base.Joiner;
import com.yt.core.dao.filter.DynamicSQLFilterImpl;
import com.yt.core.dao.filter.QueryFilter;
import com.yt.core.service.GenericServiceImpl;
import com.yt.order.api.interfaces.GroupOrderProductService;
import com.yt.order.api.interfaces.ProductService;
import com.yt.order.api.model.GroupOrderProduct;
import com.yt.order.api.model.Product;
import com.yt.order.provider.dao.ProductDao;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liujunshi on 15-12-30.
 */
public class ProductServiceImpl extends GenericServiceImpl<Product, Long> implements ProductService {
	private ProductDao dao;

	@Autowired
	private GroupOrderProductService groupOrderProductService;

	public ProductServiceImpl() {
	}

	public ProductServiceImpl(ProductDao dao) {
		super(dao);
		this.dao = dao;
	}

	public List<Product> findProductByInstitutionIDAndKeywords(Long institutionId, String keywords) {
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.setPagingBean(null);
		if (institutionId != null) {
			filter.addFilter("Q_idInstitution_L_EQ", institutionId + "");
		}
		if (keywords != null && keywords.length() > 0) {
			filter.addFilter("Q_name_S_LK", keywords);
		}
		filter.addFilter("Q_onsale_S_EQ", "1");
		return dao.find(filter);
	}

	public List<Product> findProductByGroupOrder(Long groupOrderId) {
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.setPagingBean(null);
		filter.addFilter("Q_idGroupOrder_L_EQ", groupOrderId + "");
		List<GroupOrderProduct> gpList = groupOrderProductService.find(filter);
		if(gpList == null || gpList.isEmpty()){
			return null;
		}
		List<Long> pids = new ArrayList<Long>();
		for (GroupOrderProduct obj : gpList) {
			pids.add(obj.getIdProduct());
		}
		QueryFilter pfilter = new DynamicSQLFilterImpl();
		filter.setPagingBean(null);
		pfilter.addFilter("Q_id_S_IN", Joiner.on(",").join(pids));
		filter.addFilter("Q_onsale_S_EQ", "1");

		return find(pfilter);
	}

	@Override
	public Product getProductByInstutionByName(Long institutionId, String productName) {
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.setPagingBean(null);
		filter.addFilter("Q_idInstitution_L_EQ", institutionId + "");
		filter.addFilter("Q_name_S_EQ", productName.trim());
		List<Product> productList = dao.find(filter);
		if (productList != null && productList.size() > 0) {
			return productList.get(0);
		}
		return null;
	}

	@Override
	public List<Product> getInstitutionIdAndProductIdsByProductIds(String productIds, String productName) {
		QueryFilter filter = new DynamicSQLFilterImpl();
		filter.setPagingBean(null);
		filter.addFilter("Q_id_S_IN", productIds);
		filter.addFilter("Q_name_S_EQ", productName);
		return this.dao.find(filter);
	}
}
